package com.ydjk.app.controller;


import com.ydjk.common.constant.Constants;
import com.ydjk.common.core.controller.BaseController;
import com.ydjk.common.core.domain.AjaxResult;
import com.ydjk.common.core.page.TableDataInfo;
import com.ydjk.common.core.redis.RedisCache;
import com.ydjk.common.utils.DateUtils;
import com.ydjk.common.utils.StringUtils;
import com.ydjk.common.utils.pageData.PageData;
import com.ydjk.domain.*;
import com.ydjk.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/app")
public class AppController extends BaseController {
    @Autowired
    private IJkArticleService articleService;

    @Autowired
    private IJkVideoService videoService;

    @Autowired
    private IJkBannerService bannerService;

    @Autowired
    private IJkGroupService groupService;

    @Autowired
    private IJkFllowupService fllowupService;

    @Autowired
    private IJkUserService userService;

    @Autowired
    private IJkEducationService educationService;

    @Autowired
    private IJkToolService toolService;

    @Autowired
    private IJkFllowupMessageService messageService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IJkPraiseRecordsService praiseRecordsService;

    @Autowired
    private IJkHospitalAreaService areaService;

    @Autowired
    private IJkVideoTypeService typeService;
    @Autowired
    private IJkPushTemplateService jkPushTemplateService;
    @Autowired
    private IJkInterfaceMessageService iJkInterfaceMessageService;

    @Autowired
    private IJkTemplateService jkTemplateService;

    //文章列表
    @GetMapping("/getArticlelist")
    public TableDataInfo getArticlelist(JkArticle jkArticle) {
        startPage();
        List<JkArticle> list = articleService.selectJkArticleList(jkArticle);
        return getDataTable(list);
    }

    //视频列表
    @GetMapping("/getVideolist")
    public TableDataInfo getVideolist(JkVideo jkVideo) {
        startPage();
        List<JkVideo> list = videoService.selectJkVideoList(jkVideo);
        return getDataTable(list);
    }

    //轮播图列表
    @GetMapping("/getBannerlist")
    public AjaxResult getBannerlist(JkBanner jkBanner) {
        List<JkBanner> list = bannerService.selectJkBannerList(jkBanner);
        return AjaxResult.success().put("list", list);
    }

    //文章详情
    @GetMapping(value = "/getArticleDetail")
    public AjaxResult getArticleDetail(Long id) {
        JkArticle jkArticle = articleService.selectJkArticleById(id);
        Integer pv = setPv(id, jkArticle.getArticleType());
        jkArticle.setPvCount(pv);
        return success(jkArticle);
    }

    //康复视频详情
    @GetMapping(value = "/getVideoDetail")
    public AjaxResult getVideoDetail(Long id) {
        JkVideo jkVideo = videoService.selectJkVideoById(id);
        Integer pv = setPv(id, Constants.RESOURCE_KFDL);
        jkVideo.setPvCount(pv);
        return success(jkVideo);
    }

    //扫码加入用户组
    @PostMapping("/joinGroup")
    public AjaxResult joinGroup(@RequestBody JkGroupUser groupUser) {
        if (groupUser.getUserId() == null || groupUser.getGroupId() == null) {
            return AjaxResult.error("参数错误");
        }
        return AjaxResult.success(groupService.joinGroup(groupUser));
    }

    //随访列表
    @GetMapping("/getFllowupList")
    public TableDataInfo getFllowupList(JkFllowup jkFllowup) {
        startPage();
        List<JkFllowup> jkFllowups = fllowupService.selectJkFllowupList(jkFllowup);
        return getDataTable(jkFllowups);
    }

    //提交随访
    @PostMapping("/submitFllowup")
    public AjaxResult submitFllowup(@RequestBody JkFllowup jkFllowup) {
        return toAjax(fllowupService.insertJkFllowup(jkFllowup));
    }

    //修改随访
    @PutMapping("/updateFllowup")
    public AjaxResult updateFllowup(@RequestBody JkFllowup jkFllowup) {
        return toAjax(fllowupService.updateJkFllowup(jkFllowup));
    }

    //随访详情
    @GetMapping(value = "/getFllowupDetail")
    public AjaxResult getFllowupDetail(Long id) {
        return success(fllowupService.selectJkFllowupById(id));
    }

    //修改用户-app绑定院区
    @PutMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody JkUser jkUser) {
        return toAjax(userService.updateJkUser(jkUser));
    }

    //宣教列表
    @GetMapping("/getEducationlist")
    public TableDataInfo getEducationlist(JkEducation education) {
        startPage();
        List<JkEducation> list = educationService.selectJkEducationList(education);
        return getDataTable(list);
    }

    //宣教详情
    @GetMapping(value = "/getEducationDetail")
    public AjaxResult getEducationDetail(Long id) {
        JkEducation jkEducation = educationService.selectJkEducationById(id);
        Integer pv = setPv(id, Constants.RESOURCE_XJ);
        jkEducation.setPvCount(pv);
        return success(jkEducation);
    }

    //康复用具列表
    @GetMapping("/getToollist")
    public TableDataInfo getToollist(JkTool jkTool) {
        startPage();
        List<JkTool> jkTools = toolService.selectJkToolList(jkTool);
        return getDataTable(jkTools);
    }

    //用具详情
    @GetMapping(value = "/getToolDetail")
    public AjaxResult getToolDetail(Long id) {
        JkTool jkTool = toolService.selectJkToolById(id);
        Integer pv = setPv(id, Constants.RESOURCE_KFYJ);
        jkTool.setPvCount(pv);
        return success(jkTool);
    }

    //消息列表
    @GetMapping("/getMessagelist")
    public TableDataInfo getMessagelist(JkFllowupMessage jkFllowupMessage) {
        startPage();
        List<JkFllowupMessage> jkFllowupMessages = messageService.selectJkFllowupMessageList(jkFllowupMessage);
        return getDataTable(jkFllowupMessages);
    }

    //未读消息数量
    @GetMapping("/getMessageCount")
    public AjaxResult getMessageCount(JkFllowupMessage jkFllowupMessage) {
        List<JkFllowupMessage> jkFllowupMessages = messageService.selectJkFllowupMessageList(jkFllowupMessage);
        return success(jkFllowupMessages.size());
    }

    //修改消息
    @PutMapping("/updateMessage")
    public AjaxResult updateMessage(@RequestBody JkFllowupMessage fllowupMessage) {
        return toAjax(messageService.updateJkFllowupMessage(fllowupMessage));
    }

    public Integer setPv(Long id, int type) {
        String key = "PV_" + type + "_" + id;
        Object countObj = redisCache.getCacheObject(key);
        Integer count = 0;
        if (countObj != null) {
            count = (Integer) countObj;
        }
        count += 1;
        redisCache.setCacheObject(key, count);
        return count;
    }

    //点赞
    @PostMapping("/addParise")
    public AjaxResult addParise(@RequestBody JkPraiseRecords praiseRecords) {
        praiseRecordsService.insertJkPraiseRecords(praiseRecords);
        return success().put("pariseId", praiseRecords.getId());
    }

    //取消点赞
    @DeleteMapping("/cancelParise/{id}")
    public AjaxResult cancelParise(@PathVariable Long id) {
        return toAjax(praiseRecordsService.deleteJkPraiseRecordsById(id));
    }

    //点赞详情
    @GetMapping("/getPariseDetail")
    public AjaxResult getPariseDetail(JkPraiseRecords jkPraiseRecords) {
        List<JkPraiseRecords> list = praiseRecordsService.selectJkPraiseRecordsList(jkPraiseRecords);
        return success().put("status", list.size() > 0 ? 1 : 0).put("pariseId", list.size() > 0 ? list.get(0).getId() : null);
    }

    //院区列表
    @GetMapping("/getAreaList")
    public AjaxResult getAreaList(JkHospitalArea jkHospitalArea) {
        List<JkHospitalArea> jkHospitalAreas = areaService.selectJkHospitalAreaList(jkHospitalArea);
        return success(jkHospitalAreas);
    }

    //视频分类列表
    @GetMapping("/getVideoTypeList")
    public AjaxResult getVideoTypeList(JkVideoType videoType) {
        List<JkVideoType> jkVideoTypes = typeService.selectJkVideoTypeList(videoType);
        return success(jkVideoTypes);
    }


    //视频分类列表  chen

    @RequestMapping(value = "demo", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult demo() {
        PageData pageData = getPageData();
        List<PageData> jkVideoTypes = typeService.selectDemo(pageData);
        return success(jkVideoTypes);
    }


    //获取所有用户住院信息

    @RequestMapping(value = "getAllAdmission", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getAllAdmission() {
        PageData result = new PageData();
        PageData pageData = getPageData();
        List<PageData> list = typeService.getAllAdmission(pageData);
     /*   result.put("code","200");
        result.put("data",list);*/
        return success(list);
    }


    /**
     * 是否完善 用户
     *
     * @return data: 1 未完善，2已经完善
     */

    @RequestMapping(value = "isWhetherPerfect", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult isWhetherPerfect() {
        PageData result = new PageData();
        PageData pageData = getPageData();

        if (!pageData.containsKey("openId")) {
            return AjaxResult.error("失败", "openId该参数是必填");
        }

        PageData data = typeService.isWhetherPerfect(pageData);
        if (data == null) {
            return AjaxResult.success("成功", 1);
        }

        return AjaxResult.success("成功", 2);
    }


    /**
     * 是否入院
     *
     * @return data: 1 未完善，2已经完善
     */

    @RequestMapping(value = "isAdmission", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult isAdmission() {
        PageData result = new PageData();

        PageData pageData = getPageData();

        if (!pageData.containsKey("openId")) {
            return AjaxResult.error("失败", "openId该参数是必填");

        }
        List<PageData> data = typeService.isAdmission(pageData);
        if (data.size() == 0) {
            return AjaxResult.success("成功", 1);
        }

        return AjaxResult.success("成功", 2);
    }

    /***
     *   新增入院
     * @return
     */
    @RequestMapping(value = "admissionInsert", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult admissionInsert() {
        PageData result = new PageData();
        PageData pageData = getPageData();
        typeService.admissionInsert(pageData);
        return toAjax(1);
    }


    /***
     *   编辑入院资料入院
     * @return
     */
    @RequestMapping(value = "admissionUpdata", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult admissionUpdate() {
        PageData result = new PageData();
        PageData pageData = getPageData();
        typeService.admissionUpdate(pageData);

        return toAjax(1);
    }

    /***
     *   编辑修改资料
     * @return
     */
    @RequestMapping(value = "userUpdata", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult userUpdata() {
        PageData result = new PageData();
        PageData pageData = getPageData();

        if (StringUtils.isNotNull(pageData.get("age"))) {
            pageData.put("age", DateUtils.dateTime(DateUtils.YYYY_MM_DD, pageData.get("age") + ""));
        }

        typeService.userUpdata(pageData);
        return toAjax(1);
    }


    /***
     *   接口消息推送
     * @return
     */
    @RequestMapping(value = "interfaceMessagePush", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult interfaceMessagePush() {
        PageData result = new PageData();
        PageData pageData = getPageData();

        result = jkPushTemplateService.toAddMessagePush(pageData);
        return toAjax(1);
    }

    /***
     *   获取获取所有推送消息
     * @return
     */

    @RequestMapping(value = "getInterfaceMessage", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getInterfaceMessage() {
        PageData result = new PageData();

        PageData pageData = getPageData();

        JkInterfaceMessage jkInterfaceMessage = new JkInterfaceMessage();
        if (!pageData.containsKey("userId")) {
            return AjaxResult.error("失败", "userId该参数是必填");

        }
        Long userId = Long.parseLong(pageData.get("userId") + "");
        jkInterfaceMessage.setUserId(userId);
        List<JkInterfaceMessage> data = iJkInterfaceMessageService.getInterfaceMessage(jkInterfaceMessage);

        return AjaxResult.success("成功", data);
    }

    /***
     *   根据推送后id 获取模板id
     * @return
     */

    @RequestMapping(value = "getTemplateMessage", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getTemplateMessage() {
        PageData result = new PageData();

        PageData pageData = getPageData();


        if (!pageData.containsKey("pushTemplateId")) {
            return AjaxResult.error("失败", "pushTemplateId该参数是必填");

        }

        List<JkTemplate> data = jkTemplateService.selectJkTemplateByPushTlList(pageData);

        return AjaxResult.success("成功", data);
    }

    //同步pv 暂时先不写
//    public void SyncPv(){
//        String pattern = "PV_";
//        Set<String> allkeys = redisCache.getAllkeys(pattern);
//        Iterator<String> iterator = allkeys.iterator();
//        while (iterator.hasNext()){
//            String key = iterator.next();
//            Map<String, Object> cacheMap = redisCache.getCacheMap(key);
//            Object count = cacheMap.get("count");
//            String type = key.split("_")[2];
//            String id = key.split("_")[3];
//            if(type.equals(Constants.RESOURCE_JKKP)||type.equals(Constants.RESOURCE_YDYY)){
//                JkArticle jkArticle = new JkArticle();
//                jkArticle.setId(Long.valueOf(id));
//                jkArticle.setArticlePv((Integer) count);
//                articleService.updateJkArticle(jkArticle);
//            }
//        }
//    }
}
